<template>
  <div
    :class="['unitWrapper', 'demo-autocomplete']"
    :id="'scroll' + thirdScrollIndex + '-0'"
  >
    <div class="unitTop">
      <div class="unitTitleContainer">
        <div class="unitFlag"></div>
        <div class="unitTitle">{{ chartTitle }}</div>
      </div>
      <div class="saveBtns" v-if="!isSuperToken && false">
        <div class="contentItemEditAndAIBtn AIBtn" @click="aiCreate()">
          <img src="@/assets/detail/AI_white.png" />
          {{ aiCreateStatus ? 'AI正在生成中 . . .' : 'AI生成' }}
        </div>
        <div class="contentItemEditAndAIBtn" @click="handleEditClick">
          <img src="@/assets/detail/edit_white.png" />
          {{ currentEdit ? '退出编辑' : '编辑' }}
        </div>
        <div
          class="contentItemEditAndAIBtn saveEditBtn"
          @click="save()"
          v-if="isAdmin == true && currentEdit"
        >
          <!-- <img src="@/assets/detail/save.png" /> -->
          保存
        </div>
      </div>
    </div>
    <div
      :class="{
        unitContent: true,
        colunmDirection: true,
        currentEdit: currentEdit,
        inEdit: currentEdit
      }"
    >
      <div class="secondItem">
        <div class="itemForDisplay">
          <!-- <span class="editTips" v-show="currentEdit">
            点击图表数字标签可以直接修改数据
          </span> -->
          <div class="disPlayContent">
            <div class="h100" ref="line_echartDom" v-show="!currentEdit"></div>
            <div class="regionContent">
              <div class="tips" v-show="currentEdit">
                点击图表数字标签可以直接修改数据
              </div>
              <div class="regionLineResult">
                <div
                  class="rangeDesItem"
                  v-for="(item, index) in chartData"
                  :key="index"
                >
                  <div
                    class="rangeIcon"
                    :style="`background-color:${chartColors[index]}`"
                  ></div>
                  <div
                    :class="{ rangeValue: true }"
                    @click="editValueClick(item)"
                  >
                    {{ item.value + '%' }}
                  </div>
                  <div class="rangeKey">
                    {{ item.name }}
                  </div>
                </div>
              </div>
            </div>
            <div class="itemForDisplay-right" v-show="!isClickAiCreat">
              <div class="right-title">该职业{{ chartTitle }}主要集中在</div>
              <div class="right-content">
                {{ maxName }}<span class="gap"></span>{{ maxValue }}%
              </div>
            </div>
          </div>
          <div
            :class="{
              eduSummary: true,
              hasExtendContent: extendContent.length
            }"
          >
            <p class="eduSummary" v-if="!currentEdit">{{ summary }}</p>
            <el-input
              :class="{ isClickAiCreat: isClickAiCreat }"
              ref="textArea"
              v-model="summary"
              type="textarea"
              resize="none"
              autosize
              v-else
            />
          </div>
        </div>
        <div class="itemForEdit" v-show="extendContent.length">
          <div :class="{ editBoxRight: true, inEdit: currentEdit }">
            <div
              v-for="(item, index) in extendContent"
              class="extendsItem"
              :key="index"
            >
              <!-- <div v-html="item"></div> -->
              <el-input
                type="textarea"
                autosize
                placeholder="请输入内容"
                v-model="item.content"
              />
              <div
                class="replaceByOne"
                @click="replaceByOne('second', item)"
                v-if="currentEdit"
              >
                一键替换
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  homepageQuestion,
  valueListAnalysis,
  valueListUpdate
} from '@/api/position-detail';
import { MessageBox } from 'element-ui';
import { addLog } from '@/api/position';
export default {
  props: {
    layerData: {
      type: Object,
      default: () => {}
    },
    layerId: {
      type: [Number, String],
      require: true
    },
    thirdScrollIndex: {
      type: Number || String,
      default: 1
    },
    isSuperToken: {
      type: Boolean,
      default: false
    }
  },
  name: 'eduRequireBarChart',
  mounted() {
    this.positionId = this.$route.query.id;
    this.init();
  },
  data() {
    return {
      // isSuperToken: false,
      isAdmin: true,
      isClickAiCreat: false,
      currentEdit: false,
      secondQuestionId: '',
      extendContent: [],
      firstMessages: [],
      chartTitle: '',
      positionId: '',
      summary: '', //总结话语
      myChart: '',
      maxIndex: 0,
      chartData: [], //处理好的图表展示数据
      originData: [],
      maxValue: '',
      maxName: '',
      chartColors: [
        '#00AE8B',
        '#2FCDAE',
        '#69DBC5',
        '#A0E6D8',
        '#CEF1EC',
        '#D0DBD9',
        '#DFDFDF'
      ],
      chartShadowColor: 'rgba(44, 190, 165, 0.6)'
    };
  },
  methods: {
    save() {
      this.$confirm('此操作将覆盖原有内容, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then((res) => {
        // //console.log("save------开始保存了---->");
        //后面在看看怎么保存表单的
        this.currentEdit = false;
        this.isClickAiCreat = false;
        this.extendContent = [];
        let jsonString = '';
        this.chartData.forEach((item, index) => {
          jsonString += item.name + '：' + item.value + '% ';
        });
        jsonString += this.summary;
        let questionId = this.secondQuestionId;
        const params = {
          questionContent: jsonString.replace(/<br>/g, ' '),
          id: questionId,
          ylPositionId: this.positionId
        };
        // //console.log("save------请求后结果---->", params);
        this.updateLayerValue(params);
        this.init();
      });
    },
    replaceByOne(flag, val) {
      let questionId = this.secondQuestionId;
      const params = {
        questionContent: val.content.replace(/<br>/g, ' '),
        id: questionId,
        ylPositionId: this.positionId
      };
      // //console.log("replaceByOne------请求前参数---->", params);
      valueListAnalysis(params).then((res) => {
        if (res.code == 200) {
          this.$confirm('此操作将覆盖原有内容, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.originData = [];
            res.data.forEach((item) => {
              if (!item.description || !item.layerValue) return;

              if (item.description == '总结') {
                this.summary = item.layerValue;
                return;
              }
              this.originData.push({
                name: item.description,
                value: item.layerValue
              });
            });
            //还要发送请求给后端保存。。。
            // //console.log("originData------请求后结果--2-->", this.originData);
            this.updateLayerValue(params);
            this.init();
          });
        } else {
          // //console.log("内容解析失败了！请尝试重新生成！");
        }
      });
    },
    updateLayerValue(params) {
      // //console.log("updateLayerValue----请求前结果------>", params);
      valueListUpdate(params).then((res) => {
        this.$message({
          type: 'success',
          message: '修改成功!'
        });
      });
    },
    handleEditClick() {
      this.currentEdit = !this.currentEdit;
      if (this.currentEdit) {
        this.$message({
          type: 'success',
          message: '点击百分比数字可以单个编辑数据',
          offset: 400
        });
      }
    },
    handleData(data) {
      let chartData = [];
      // //console.log("chartData----前--->", data);
      data.forEach((item) => {
        let dataItem = {
          value: '',
          name: ''
        };
        if (parseInt(item.value.slice(0, item.value.length - 1)) > 0) {
          dataItem.value = parseInt(item.value.slice(0, item.value.length - 1));
          dataItem.name = item.name;
          chartData.push(dataItem);
        }
      });
      // //console.log("chartData---后---->", chartData);
      return chartData;
    },
    getMaxValue() {
      return this.chartData[this.maxIndex].value;
    },
    getMaxName() {
      return this.chartData[this.maxIndex].name;
    },
    editValueClick(item) {
      if (this.currentEdit) {
        const nowName = item.name;
        MessageBox.prompt(`请输入${nowName}占比新的值：`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^(?:0|[1-9][0-9]?|100)$/,
          inputErrorMessage: '输入格式不正确'
        })
          .then(({ value }) => {
            // //console.log("originData------请求后结果--3-->", this.originData);
            this.originData.forEach((item) => {
              if (item.name == nowName) {
                item.value = value + '%';
              }
            });
            this.handleChartValueChange(nowName, value);
          })
          .catch((e) => {
            //console.log("e", e);
            // Message({
            //   type: "info",
            //   message: "取消输入",
            // });
          });
      }
    },
    init() {
      if (!this.$refs['line_echartDom']) return;
      this.chartData = this.handleData(this.originData);
      this.myChart = this.$echarts.init(this.$refs['line_echartDom']);
      let option = {
        color: this.chartColors,
        series: [
          {
            type: 'pie',
            label: {
              show: false,
              position: 'center',
              // 高亮样式。
              emphasis: {
                show: true,
                fontSize: '30',
                fontWeight: 'bold',
                fontFamily: 'D-DIN-PRO-600-SemiBold'
              },
              formatter: function (params) {
                return (
                  '{a|' + params.value + '%}' + '\n' + '{b|' + params.name + '}'
                );
              },
              rich: {
                a: {
                  color: '#333',
                  fontWeight: 'bold',
                  fontSize: 24,
                  height: 40,
                  backgroundColor: 'white',
                  fontFamily: 'D-DIN-PRO-600-SemiBold'
                },
                b: {
                  color: '#888',
                  fontSize: 14,
                  backgroundColor: 'white'
                }
              }
            },
            labelLine: {
              show: false
            },

            // 高亮样式。
            itemStyle: {
              borderWidth: 0,
              borderColor: this.chartShadowColor,
              shadowBlur: 0,
              shadowOffsetX: 0,
              shadowOffsetY: 0,
              shadowColor: this.chartShadowColor, //6638FF
              emphasis: {
                borderWidth: 1.5,
                borderColor: 'rgb(255,255,255,0.6)',
                shadowBlur: 8,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                shadowColor: this.chartShadowColor //6638FF
              }
            },
            data: this.chartData,
            radius: ['45%', '70%']
          }
        ]
      };
      try {
        option && this.myChart.setOption(option);
      } catch (error) {
        this.myChart.resize();
        //console.log("erro", this.chartData);
      }

      let maxIndex = 0;
      let maxValue = -Infinity;

      for (let i = 0; i < this.chartData.length; i++) {
        if (this.chartData[i].value > maxValue) {
          maxValue = this.chartData[i].value;
          maxIndex = i;
        }
      }
      this.maxIndex = maxIndex;
      this.maxName = this.chartData[maxIndex].name;
      this.maxValue = this.chartData[maxIndex].value;

      // console.log(
      //   "myChart------xxxxxxxxx--->",
      //   this.chartData,
      //   maxIndex,
      //   maxValue
      // );
      getDefaultSelected(this.myChart);
      function getDefaultSelected(myChart) {
        // //console.log("myChart------xxxxxxxxx--->", maxIndex);
        let index = maxIndex;

        myChart.dispatchAction({
          type: 'highlight',
          seriesIndex: 0,
          dataIndex: maxIndex
        });
        myChart.on('mouseover', (e) => {
          if (e.dataIndex !== index) {
            myChart.dispatchAction({
              type: 'downplay',
              seriesIndex: 0,
              dataIndex: index
            });
          }
        });
        myChart.on('mouseout', (e) => {
          index = e.dataIndex;
          myChart.dispatchAction({
            type: 'highlight',
            seriesIndex: 0,
            dataIndex: e.dataIndex
          });
        });
      }
      window.addEventListener('resize', () => {
        if (this.myChart) {
          this.myChart.resize();
        }
      });
      this.myChart.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex: 1
      });
    },
    handleChartValueChange(nowName, value) {
      // //console.log("originData------请求后结果--4-->", this.originData);
      this.init();
    },
    calcTextAreaHeight() {
      if (!this.$refs['textArea']) return;
      const el = this.$refs['textArea'].$el.querySelector(
        '.el-textarea__inner'
      );
      el.style.height = el.scrollHeight + 'px';
    },
    async aiCreate() {
      // //console.log("------点击AI生成-------->");
      this.isClickAiCreat = true;
      if (this.aiCreateStatus) {
        this.$message({
          type: 'warning',
          message:
            '已有AI正在生成中，等待生成内容结束或F5刷新页面再次点击AI生成!'
        });
        return;
      } else {
        this.$set(this.layerData, 'hasExtendContent', true);
        //重新计算textarea的高度
        setTimeout(() => {
          this.$nextTick(() => {
            this.calcTextAreaHeight();
          });
        }, 200);
        // this.currentEdit = true;
        let textEl = document.querySelectorAll('.AIBtn'); // 获取要添加省略号的元素
        textEl.forEach((item) => {
          item.classList.add('AILoading'); // 添加类名，启动动画效果
        });
      }

      //获取问题
      const name =
        this.$route.query.name != undefined ? this.$route.query.name : '';

      const questionRes1 = await this.reqGetQuestionbyId(this.secondQuestionId);
      // //console.log("获取问题questionRes1------->", questionRes1);
      this.chatKey1 = questionRes1.data.questionContent.replace(/{}/g, name);

      //同时发送两个问题给chatGPT
      this.firstMessages.push({
        role: 'user',
        content: this.chatKey1
      });
      const agentData1 = {
        userId: '',
        userName: '',
        messages: this.firstMessages
      };
      this.firstMessages = [];
      this.sendMsg1 = JSON.stringify(agentData1);

      this.$set(this.extendContent, this.extendContent.length, { content: '' });
      try {
        this.$bus.$emit(
          'send',
          this.sendMsg1,
          this.initMessageBackForFirst,
          this.wsError
        );
      } catch (error) {
        //console.log("发送ws报错", error);
      }

      this.$message.success({
        message: 'AI生成内容中...',
        offset: '400'
      });
      addLog({ logType: '10' });
    },
    initMessageBackForFirst(res) {
      // //console.log("initMessageBackForFirst---------->", res);
      const msg = res.choices && res.choices[0];
      if (msg.delta.role === 'assistant') {
        return;
      }
      if (msg.finish_reason === 'stop' || msg.finish_reason === 'done') {
        this.loading = false;
        this.currentRole = '';
        let textEl = document.querySelectorAll('.AIBtn');
        textEl.forEach((item) => {
          item.classList.remove('AILoading');
        });

        return;
      }
      if (msg.delta.content) {
        var tempStr = msg.delta.content;
        if (tempStr) {
          tempStr = tempStr.replace(/(\r\n|\n|\r)+/g, '<br>');
        }
        let len = this.extendContent ? this.extendContent.length - 1 : 0;
        this.$set(
          this.extendContent[len],
          'content',
          (this.extendContent[len].content += tempStr)
        );
      }
    },
    reqGetQuestionbyId(questionId) {
      return homepageQuestion({ questionId });
    },
    wsError() {
      // if (this.isStoped) {
      //   this.isContinue = false;
      // } else {
      //   this.isContinue = true;
      // }
      //console.log("连接失败，请重试");
    }
  },
  computed: {
    aiCreateStatus() {
      // return this.$store.state.ws.aiCreateStatus;
      return false;
    }
  },
  watch: {
    layerData: {
      handler(newValue, oldValue) {
        if (!this.secondQuestionId) {
          this.secondQuestionId = newValue.questionId;
          if (this.secondQuestionId === '99') {
            //学历要求
            this.chartColors = [
              '#1D5AFF',
              '#3E87FF',
              '#75A9FD',
              '#A0C3FF',
              '#BADCFF',
              '#D0DBD9',
              '#DFDFDF'
            ];
            this.chartShadowColor = 'rgba(102, 56, 255, 0.6)';
          } else {
            this.chartColors = [
              '#00AE8B',
              '#2FCDAE',
              '#69DBC5',
              '#A0E6D8',
              '#CEF1EC',
              '#D0DBD9',
              '#DFDFDF'
            ];
            this.chartShadowColor = 'rgba(44, 190, 165, 0.6)';
          }
        }
        // //console.log("radarChartLayerData-----学历要求-----》", newValue);
        this.originData = [];
        const item = newValue;
        this.chartTitle = item.title;
        item.data.forEach((item) => {
          if (item.description == '总结') {
            this.summary = item.layerValue;
            return;
          }

          try {
            this.originData.push({
              name: item.description,
              value: item.layerValue
            });
          } catch (error) {
            //console.log("error", error);
          }
        });
        // //console.log("originData------请求后结果--1-->", this.originData);
      },
      immediate: true
    }
  }
};
</script>

<style lang="scss" scoped>
.unitWrapper {
  display: flex;
  flex-direction: column;
  // background-color: aqua;
  // height: 300px;
  width: 100%;
  // height: 100px;
  min-width: 48%;
  margin-bottom: 14px;
  &.wider {
    width: 200%;
  }
  .unitTop {
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: linear-gradient(260deg, #48a8ff 0%, #1470fa 100%);
    border-radius: 8px 8px 0px 0px;
    opacity: 0.87;
    padding: 10px 18px;
    .unitTitleContainer {
      display: flex;
      align-items: center;
      .unitFlag {
        width: 5px;
        height: 15px;
        background: #ffffff;
        border-radius: 3px;
        margin-right: 8px;
      }
      .unitTitle {
        height: 25px;
        font-size: 18px;
        font-family: PingFangSC-Medium, PingFang SC;
        font-weight: 500;
        letter-spacing: 0.3px;
        color: #ffffff;
        line-height: 25px;
      }
    }

    .saveBtns {
      display: flex;
      height: 32px;
      align-items: center;
      justify-content: center;
      padding-right: 10px;
      .contentItemEditAndAIBtn {
        line-height: 32px;
        margin: 0 10px 0 15px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #ffffff;
        display: flex;
        align-items: center;
        cursor: pointer;
        img {
          width: 22px;
          height: 22px;
        }
      }
      .saveEditBtn {
        width: 57px;
        height: 26px;
        color: #3674ff;
        background-color: #fff;
        border-radius: 4px;
        justify-content: center;
      }
    }
  }
  .unitContent {
    min-height: 280px;
    display: flex;
    flex-wrap: wrap;
    background: #ffffff;
    border-radius: 0px 0px 8px 8px;
    justify-content: center;
    align-items: center;
    border: 1px solid #c8cee9;
    width: 100%;
    &.colunmDirection {
      flex-direction: column;
    }
    &.inEdit {
      .rangeValue {
        background-color: rgba(238, 238, 238, 1);
        text-align: center;
        font-size: 20px !important;
        font-family: D-DIN-PRO-600-SemiBold !important;
        font-weight: 600;
        color: #555555;
        line-height: 19px;
        padding: 7px 9px;
        width: auto !important;
      }
      .regionLineResult {
        background-color: transparent !important;
      }
      .itemForDisplay {
        /* border: 1px solid #709cff; */
        /* border-radius: 0px 0px 8px 8px; */
      }
    }
    .secondItem {
      display: flex;
      justify-content: center;
      // align-items: center;
      // padding-top: 41px;
      flex: 1;
      .itemForDisplay {
        display: block;
        // justify-content: space-between;
        // align-items: center;
        flex: 1;
        width: 50%;
        padding: 20px 20px 0px 20px;
        // padding: 0px 0px;
        min-width: 422px;
        // margin-left: 51px;
        // flex-direction: column;
        // max-height: 300px;
        .editTips {
          position: relative;
          font-size: 14px;
          font-family: PingFang-SC-Bold, PingFang-SC;
          color: #aaa;
          line-height: 28px;
          padding-bottom: 5px;
          padding-top: 8px;
        }
        .disPlayContent {
          display: flex;
          justify-content: space-around;
          align-items: center;
        }
      }
      .itemForDisplay-right {
        display: block;
        width: 30%;
        margin-left: 20px;
        .right-title {
          color: #555;
          font-size: 16px;
          margin-bottom: 10px;
        }
        .right-content {
          color: #1b78ff;
          font-size: 22px;
          font-weight: bold;
          font-family: D-DIN-PRO-Bold, D-DIN-PRO;
        }
        .gap {
          margin-right: 30px;
        }
      }
      .h100 {
        min-width: 250px;
        min-height: 220px;
      }
      .regionContent {
        .tips {
          text-align: center;
          position: relative;
          font-size: 14px;
          font-family: PingFang-SC-Bold, PingFang-SC;
          color: #aaa;
          line-height: 28px;
          padding-bottom: 5px;
          padding-top: 8px;
        }
        .regionLineResult {
          display: flex;
          flex-wrap: wrap;
          // flex: 0.5;
          max-width: 400px;
          height: fit-content;
          // margin-left: 20px;
          /* justify-content: left; */
          justify-content: flex-start;
          // height: 150px;
          background-color: #f3f7ff;
          border-radius: 8px;
          padding: 10px 5px;
          .rangeDesItem {
            display: flex;
            flex-wrap: wrap;
            min-width: 170px;
            justify-content: flex-start;
            align-items: center;
            margin: 10px 10px;
            // height: 40px;
            .rangeIcon {
              width: 10px;
              height: 10px;
              border-radius: 3px;
              margin-right: 10px;
              // background-color: #0b6eff;
            }
            .rangeKey {
              width: 80px;
              // height: 40px;
              color: #555;
              font-size: 15px;
              // font-weight: bold;
            }
            .rangeValue {
              // display: block;
              width: 60px;
              font-size: 16px;
              // height: 40px;
              color: #555;
              font-weight: bold;
              margin-right: 10px;
              font-family: D-DIN-PRO-600-SemiBold;
            }
          }
        }
      }
      .itemForEdit {
        flex: 1;
        min-width: 48%;
        .editBoxRight {
          flex: 1;
          padding: 0px 16px 12px 16px;
          font-size: 15px;
          font-family: PingFangSC-Regular, PingFang SC;
          font-weight: 400;
          color: #4b6aaf;
          line-height: 27px;
          position: relative;
          border-radius: 0px 6px 6px 0px;
          min-height: 300px;
          padding-bottom: 20px;
          width: 100%;
          .extendsItem {
            position: relative;
            padding-bottom: 35px;
            padding: 20px 16px 12px 16px;

            width: 100%;
            div {
              width: 100%;
            }
            .replaceByOne {
              display: flex;
              justify-content: flex-end;
              position: relative;
              bottom: 0;
              right: 14px;
              cursor: pointer;
              color: #4880ff;
            }
          }
          &.inEdit {
            background: #f5f9ff;
            border-left: 1px solid #709cff;
            height: 100%;
          }
        }
      }
    }
    .eduSummary {
      width: 100%;
      padding-bottom: 5px;
      color: #999999;
      font-size: 14px;
      word-break: break-all;
      line-height: 28px;
      letter-spacing: 0.2px;
      // overflow: hidden;
      // white-space: nowrap;
      // text-overflow: ellipsis;
      ::v-deep .el-textarea__inner {
        padding-top: 0;
        /* min-height: 500px; */
        resize: none;
        height: 100%;
        line-height: 26px;
      }
      p {
        margin-top: 0px;
      }
      .isClickAiCreat {
        ::v-deep.el-textarea__inner {
          // height: 26vh !important;
          /* background-color: #1470fa; */
        }
      }
    }
  }
  .currentEdit {
    border: 1px solid #709cff;
  }
  ::v-deep .el-input__inner {
    /* height: 32px; */
    background: #eeeeee;
    border-radius: 2px;
    font-size: 16px;
    font-family: PingFang-SC-Bold, PingFang-SC;
    font-weight: bold;
    color: #333333;
    line-height: 28px;
    outline: none;
  }
  ::v-deep .el-textarea__inner {
    padding: 12px 0px 17px 12px;
  }
}
</style>
